# Create your views here.
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import docker

client = docker.from_env()


# 列出所有镜像
@csrf_exempt
def image_ls(request):
    if request.method == 'GET':
        try:
            images = client.images.list()
            image_list = []
            for image in images:
                image_id = image.id
                image_name = image.tags[0].split(':')[0]
                image_tag = image.tags[0].split(':')[1]
                image_size = image.attrs['Size']
                image_create_time = image.attrs['Created']
                image_architecture = image.attrs['Architecture']
                image_os = image.attrs['Os']
                image_list.append({'image_id': image_id, 'image_name': image_name, 'image_tag': image_tag,
                                   'image_size': image_size, 'image_create_time': image_create_time,
                                   'image_architecture': image_architecture, 'image_os': image_os})
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '镜像列表获取失败'})
        return JsonResponse({'status': 200, 'msg': '镜像列表获取成功', 'data': image_list})
    pass


# 拉取镜像
@csrf_exempt
def image_pull(request):
    if request.method == 'POST':
        image_name = request.POST.get('image_name')
        image_tag = request.POST.get('image_tag')
        if image_tag is None:
            image_tag = 'latest'
        try:
            client.images.pull(image_name, tag=image_tag)
            # 获取该镜像的镜像ID，镜像名，镜像标签，镜像大小，镜像创建时间，镜像架构，镜像操作系统
            image = client.images.get(image_name + ':' + image_tag)
            image_id = image.id
            image_name = image.tags[0].split(':')[0]
            image_tag = image.tags[0].split(':')[1]
            image_size = image.attrs['Size']
            image_create_time = image.attrs['Created']
            image_architecture = image.attrs['Architecture']
            image_os = image.attrs['Os']
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '镜像拉取失败'})
        return JsonResponse({'status': 200, 'msg': '镜像拉取成功',
                             'data': {'image_id': image_id, 'image_name': image_name, 'image_tag': image_tag,
                                      'image_size': image_size, 'image_create_time': image_create_time,
                                      'image_architecture': image_architecture, 'image_os': image_os}})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass


# 删除镜像
@csrf_exempt
def image_rm(request):
    if request.method == 'POST':
        image_id = request.POST.get('image_id')
        try:
            client.images.remove(image_id)
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '镜像删除失败'})
        return JsonResponse({'status': 200, 'msg': '镜像删除成功'})
    pass


# 添加镜像标签
@csrf_exempt
def image_tag(request):
    if request.method == 'POST':
        image_id = request.POST.get('image_id')
        image_name = request.POST.get('image_name')
        image_tag = request.POST.get('image_tag')
        try:
            client.images.get(image_id).tag(image_name, image_tag)
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '镜像标签添加失败'})
        return JsonResponse({'status': 200, 'msg': '镜像标签添加成功'})
    pass


# 搜索镜像
@csrf_exempt
def image_search(request):
    if request.method == 'POST':
        keyword = request.POST.get('keyword')
        try:
            images = client.images.search(keyword)
            image_list = []
            for image in images:
                image_name = image['name']
                image_description = image['description']
                image_list.append({'image_name': image_name, 'image_description': image_description})
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '镜像搜索失败'})
        return JsonResponse({'status': 200, 'msg': '镜像搜索成功', 'data': image_list})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass


# 提交容器为镜像
@csrf_exempt
def image_commit(request):
    if request.method == 'POST':
        container_id = request.POST.get('container_id')
        image_name = request.POST.get('image_name')
        image_tag = request.POST.get('image_tag')
        if image_tag is None:
            image_tag = 'latest'
        try:
            client.containers.get(container_id).commit(repository=image_name, tag=image_tag)
            # 获取该镜像的镜像ID，镜像名，镜像标签，镜像大小，镜像创建时间，镜像架构，镜像操作系统
            image = client.images.get(image_name + ':' + image_tag)
        except Exception as e:
            print(e)
            return JsonResponse({'status': 400, 'msg': '容器提交为镜像失败'})
        return JsonResponse({'status': 200, 'msg': '容器提交为镜像成功',
                             'data': {'image_id': image.id, 'image_name': image.tags[0].split(':')[0],
                                      'image_tag': image.tags[0].split(':')[1], 'image_size': image.attrs['Size'],
                                      'image_create_time': image.attrs['Created'],
                                      'image_architecture': image.attrs['Architecture'], 'image_os': image.attrs['Os']}})
    else:
        return JsonResponse({'status': 400, 'msg': '请求方式错误'})
    pass
